/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.web.wizards.template;

import cn.easyplatform.entities.beans.page.PageBean;
import cn.easyplatform.entities.beans.table.TableField;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.entity.CheckCmd;
import cn.easyplatform.studio.web.editors.GridEditorCallback;
import cn.easyplatform.studio.web.editors.TableInfo;
import cn.easyplatform.studio.web.editors.support.CodeFormatter;
import cn.easyplatform.studio.web.editors.support.ZulXsdUtil;
import cn.easyplatform.studio.web.views.impl.AbstractView;
import org.apache.commons.lang3.math.NumberUtils;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.*;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class MobilePage3 extends AbstractTemplate {

    protected TableInfo mainTable;

    protected TableInfo selectedTable;

    protected String selectedList;

    private Vlayout temp;

    private Grid grid;

    @Override
    protected void initComponents(Component root) {
        for (Component c : root.getFellows()) {
            if (c instanceof A || c instanceof Button)
                c.addEventListener(Events.ON_CLICK, this);
        }
        temp = (Vlayout) root.getFellow("temp");
        grid = (Grid) root.query("grid");
        grid.addEventListener(Events.ON_CHANGE, this);
        root.query("groupbox").addEventListener(Events.ON_CLICK, this);
    }

    @Override
    protected void dispatch(Event evt) {
        Component c = evt.getTarget();
        if (c == grid) {
            selectedTable = (TableInfo) evt.getData();
            onCreate(grid, selectedTable);
            selectedList = null;
        } else if (c instanceof Groupbox) {
            grid = (Grid) c.query("grid");
            for (Component co : c.getRoot().queryAll("groupbox")) {
                ((Groupbox) co).setStyle("border:none");
            }
            ((Groupbox) c).setStyle("border:1px solid #87CEFA");
        } else if (c.getId().equals("addGroup")) {
            addGroup();
        } else if (c.getId().equals("delete")) {
            temp.removeChild(grid.getParent());
            grid = (Grid) temp.query("grid");
        } else if (c.getId().equals("addList")) {
            AbstractView.createTableView(
                    new GridEditorCallback(grid,
                            Labels.getLabel("wizard.table")), true, evt.getTarget())
                    .doOverlapped("right,center");
        }
    }

    private void addGroup() {
        Groupbox groupbox = new Groupbox();
        groupbox.setHflex("1");
        groupbox.setMold("3d");
        groupbox.setStyle("border:none");
        Caption caption = new Caption();
        caption.setLabel("标题");
        Grid grid = new Grid();
        grid.setHflex("1");
        grid.setStyle("border:none");
        grid.appendChild(new Rows());
        this.grid = grid;
        grid.addEventListener(Events.ON_CHANGE, this);
        groupbox.appendChild(caption);
        groupbox.appendChild(grid);
        groupbox.addEventListener(Events.ON_CLICK, this);
        temp.appendChild(groupbox);
    }

    protected String getContent() {
        StringBuilder sb = new StringBuilder();
        sb.append("<vlayout hflex=\"1\" vflex=\"1\" >");
        for (Component c : temp.getChildren()) {
            grid = (Grid) c.query("grid");
            sb.append("<groupbox hflex=\"1\" mold=\"3d\" style=\"border:none\">")
                    .append("<caption label=\"标题\"/>")
                    .append("<grid hflex=\"1\" style=\"border:none\">")
                    .append("<rows>");
            for (Component co : grid.getRows().getChildren()) {
                sb.append("<row>");
                for (Component comp : co.getChildren()) {
                    sb.append("<label value=\"" + ((Label) comp).getValue() + "\" />");
                }
                sb.append("</row>");
            }
            sb.append("</rows>");
            sb.append("</grid>");
            sb.append("</groupbox>");
        }
        sb.append("</vlayout>");

        return CodeFormatter.formatXML(ZulXsdUtil.buildDocument(sb.toString()));
    }

    protected void onCreate(Grid list, TableInfo selectedTable) {
        Components.removeAllChildren(list.getRows());
        int index = 0;
        Row row = new Row();
        for (TableField tf : selectedTable.getFields()) {
            Label label = new Label(tf.getDescription());
            row.appendChild(label);
            row.appendChild(new Label());
            index++;
            if (index % 2 == 0) {
                list.getRows().appendChild(row);
                row = new Row();
            }
        }
        if (index % 2 != 0)
            list.getRows().appendChild(row);
    }


    @Override
    public PageBean getEntity() {
        PageBean pb = new PageBean();
        pb.setTable(mainTable == null ? null : mainTable.getTable());
        pb.setAjax(getContent());
        return pb;
    }

    protected String fetchId() {
        String id = (String) grid.getRoot().getAttribute("id");
        if (id.length() > 4) {
            // 功能ID：SYSCOM50
            // 页面ID：SYSCOM50PY01
            // 列表ID：SYSCOM50QY01
            // 子表列表：SYSCOM50QY02
            // 子表页面：SYSCOM50PY02
            String suffix = id.substring(id.length() - 4, id.length());
            String preffix = id.substring(0, id.length() - 4);
            if (suffix.startsWith("PY")
                    && NumberUtils.isNumber(suffix.substring(2))) {// 符合id命名规范
                for (int i = 1; i <= 99; i++) {
                    String entityId = preffix + "QY" + (i < 10 ? "0" + i : i);
                    if (!StudioApp.execute(new CheckCmd(entityId))) {
                        id = entityId;
                        break;
                    }
                }
            } else {// 不符合规范的,在页面id的基础上从01开始累加
                for (int i = 1; i <= 99; i++) {
                    String entityId = id + (i < 10 ? "0" + i : i);
                    if (!StudioApp.execute(new CheckCmd(entityId))) {
                        id = entityId;
                        break;
                    }
                }
            }
        } else {// 不符合规范的,在页面id的基础上从01开始累加
            for (int i = 1; i <= 99; i++) {
                String entityId = id + (i < 10 ? "0" + i : i);
                if (!StudioApp.execute(new CheckCmd(entityId))) {
                    id = entityId;
                    break;
                }
            }
        }
        return id;
    }
}
